package com.ccx.coachsite.ui.login;

import org.json.JSONObject;

import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.StringUtil;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv1.OAuthV1;
import com.tencent.weibo.oauthv1.OAuthV1Client;
import com.tencent.weibo.utils.QHttpClient;
import com.tencent.weibo.webview.OAuthV1AuthorizeWebView;

import android.app.Activity;
import android.content.Intent;

public class QQWeibo extends WeiboBase {

	private OAuthV1 oAuth;
	
	public QQWeibo(Activity superActivity) {
		super(superActivity);
		loginType = 2;
		weiboTitle="腾讯微博";
		oauthCallback = "null";
		oauthConsumeKey = "801115505";
		oauthConsumerSecret = "be1dd1410434a9f7d5a2586bab7a6829";
		
		oAuth=new OAuthV1(oauthCallback);
        oAuth.setOauthConsumerKey(oauthConsumeKey);
        oAuth.setOauthConsumerSecret(oauthConsumerSecret);
        
      //关闭OAuthV1Client中的默认开启的QHttpClient。
        OAuthV1Client.getQHttpClient().shutdownConnection();
      		
        //为OAuthV1Client配置自己定义QHttpClient。
        OAuthV1Client.setQHttpClient(new QHttpClient());
	}
	
	public  boolean doQAuth()
	{
		Intent intent;
		boolean result = false;
		try {
			oAuth=OAuthV1Client.requestToken(oAuth);
			intent = new Intent(superActivity, OAuthV1AuthorizeWebView.class);//创建Intent，使用WebView让用户授权
	        intent.putExtra("oauth", oAuth);
	        superActivity.startActivityForResult(intent,1);
	        result = true;
		} catch (Exception e) {
			result = false;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	public boolean onQAuthResult(Intent data)
	{
		boolean result = false;
		if(data != null)
		{
			UserAPI userAPI;
			oAuth=(OAuthV1) data.getExtras().getSerializable("oauth");
			try{
				oAuth=OAuthV1Client.accessToken(oAuth);
				
				/*
				 * 注意：此时oauth中的Oauth_token和Oauth_token_secret将发生变化，用新获取到的
				 * 已授权的access_token和access_token_secret替换之前存储的未授权的request_token
				 * 和request_token_secret.
				 */
			} catch (Exception e) {
				result = false;
				e.printStackTrace();
			}
			
			userAPI=new UserAPI(OAuthConstants.OAUTH_VERSION_1);
            try {
                String response=userAPI.info(oAuth, "json");//获取用户信息
                JSONObject jsonObject = new JSONObject(response);
    			JSONObject respsonObject = jsonObject.getJSONObject("data");
    			weiboName = respsonObject.getString("nick");
    			weiboHeader = respsonObject.getString("head");
    			weiboId = respsonObject.getString("openid");
                //Log.e(response);
                if(!StringUtil.isEmpty(weiboId))
                {
                	result = true;
                }
            } catch (Exception e) {
            	result = false;
                e.printStackTrace();
            }
            userAPI.shutdownConnection();
		}
		return result;
	}
}
